package org.example.service.impl;

import cn.hutool.core.util.ObjectUtil;
import org.example.dao.ISysDepartmentDao;
import org.example.dao.ISysMenuDao;
import org.example.dao.ISysUserDao;
import org.example.domain.entity.SysMenu;
import org.example.domain.entity.SysRole;
import org.example.domain.entity.SysUser;
import org.example.domain.vo.LoginUserVo;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailImpl implements UserDetailsService {
    private final ISysUserDao sysUserDao;
    private final ISysDepartmentDao sysDepartmentDao;
    private final ISysMenuDao sysMenuDao;

    public UserDetailImpl(ISysUserDao sysUserDao, ISysDepartmentDao sysDepartmentDao, ISysMenuDao sysMenuDao) {
        this.sysUserDao = sysUserDao;
        this.sysDepartmentDao = sysDepartmentDao;
        this.sysMenuDao = sysMenuDao;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserDao.selectByUsername(username);
        LoginUserVo loginUserVo = new LoginUserVo();
        if(ObjectUtil.isNotNull(user)){
            /*List<SysDepartment> sysDepartments = sysDepartmentDao.selectDeptsByUserId(user.getId());
            user.setDepartments(sysDepartments);*/
            List<SysRole> sysRole = user.getRoles();
            List<Long> roleIds = sysRole.stream().map(SysRole::getId).collect(Collectors.toList());
            List<SysMenu> sysMenus = sysMenuDao.selectMenuByRoleId(roleIds);
            List<String> perm = sysMenus.stream().map(SysMenu::getPerms).collect(Collectors.toList());
            user.setPerms(perm);
            loginUserVo.setUser(user);
            loginUserVo.setId(user.getId());
        }else {
            throw new  RuntimeException("用户不存在！");
        }
        return loginUserVo;
    }
}
